package com.yupi.lanhai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yupi.lanhai.common.ErrorCode;

import java.util.ArrayList;
import java.util.Map.Entry;
import com.yupi.lanhai.contant.UserConstant;
import com.yupi.lanhai.exception.BusinessException;
import com.yupi.lanhai.model.domain.User;
import com.yupi.lanhai.service.UserService;
import com.yupi.lanhai.mapper.UserMapper;
import com.yupi.lanhai.utils.AlgorithmUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.yupi.lanhai.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "sjf";

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @param planetCode    星球编号
     * @return 新用户 id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编号重复");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request
     * @return 脱敏后的用户信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8) {
            return null;
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setTags(originUser.getTags());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 根据标签搜索用户
     * @param tagNameList
     * @return
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagNameList) {
        //判断参数是否为空
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //创建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //like '%Java% and like '%Python%'
        //queryWrapper的like方法可以构成like '%tagName%的查询条件
        //此处使用循环，将标签列表构成like '%Java% and like '%Python%'的查询条件
        for (String tagName : tagNameList) {
            queryWrapper = queryWrapper.like("tags",tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);

        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     * 用户更改个人信息
     * @param user
     * @param request
     * @return
     */
    @Override
    public int updateUserInfo(User user, HttpServletRequest request) {
        //从cookie中获取当前用户信息
        User UserAttribute = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        Long cookieId = UserAttribute.getId();

        //判断是否是自己修改信息
        Long userId = user.getId();
        if(!userId.equals(cookieId)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        return userMapper.updateById(user);
    }

    /**
     * 主页推荐
     * @param pageSize 每页展示数
     * @param pageNum 展示第几页
     * @param request
     * @return
     */
    public List<User> recommendUsers(long pageSize, long pageNum,HttpServletRequest request){
        //获取当前用户信息
        User attribute = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        if(attribute==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = attribute.getId();

        String redisKey = String.format("sjf:user:recommend:%s", id);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        // 如果有缓存，直接读缓存
        List<User> userList = (List<User>)valueOperations.get(redisKey);
        if (userList != null) {
            return userList;
        }
        // 无缓存，查数据库
        // 创建分页对象，pageNum为当前页码，pageSize为每页显示的记录数
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Page<User> page = new Page<>(pageNum, pageSize);
        //todo 分页查询有误，查询的是全的数据
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);
        List<User> records = userPage.getRecords();

        // 写缓存
        try {
            valueOperations.set(redisKey, records, 30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error", e);
        }
        return records;
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    /**
     * 是否为管理员
     *
     * @param loginUser
     * @return
     */
    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser != null && loginUser.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    /**
     * 获取当前用户信息
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        User userObj = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return userObj;
    }

    /**
     * 推荐相似度最高的用户
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //只查找ID和tags字段，优化sql语句
        queryWrapper.select("id", "tags");
        //排除tags为空的用户
        queryWrapper.isNotNull("tags")
                // ne：not equal，排除loginUser本身
                .ne("id", loginUser.getId());

        //查询出相关用户的List集合
        List<User> userList = this.list(queryWrapper);

        //获取当前用户的tags标签
        String tags = loginUser.getTags();
        Gson gson = new Gson();
        //获取loginUser的tags字符串，并使用Gson库将其解析成一个标签列表tagList。
        //由于Java的泛型擦除机制，直接传递List<String>.class并不能正确表达泛型信息，因此需要使用TypeToken来准确指定类型。
        //调用这个匿名内部类的getType()方法，它返回了一个Type对象，这个对象包含了List<String>的类型信息。
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {}.getType());

        // 使用流操作来获取与loginUser最相似的前num个用户
        List<User> topUserList = userList.stream()
                //排除tags为空的用户。
                .filter(user -> !StringUtils.isBlank(user.getTags()))
                .map(user -> {
                    //对每个用户，解析其tags字符串为标签列表userTagList
                    List<String> userTagList = gson.fromJson(user.getTags(), new TypeToken<List<String>>() {}.getType());
                    //计算loginUser与该用户的tags之间的相似度（distance）
                    long distance = AlgorithmUtils.minDistance(tagList, userTagList);
                    //将用户和距离封装进SimpleEntry。
                    return new AbstractMap.SimpleEntry<>(user, distance);
                })
                //根据距离对SimpleEntry进行升序排序，距离越小表示越相似。
                .sorted(Map.Entry.comparingByValue())
                //只保留前num个最相似的用户。
                .limit(num)
                //从SimpleEntry中提取出用户对象。
                .map(Entry::getKey)
                //调用getSafetyUser方法，去除敏感信息。
                .map(this::getSafetyUser)
                .collect(Collectors.toList());

        //获取匹配用户的ID集合
        List<Long> userIds = topUserList.stream()
                .map(User::getId)
                .collect(Collectors.toList());
        List<User> resultUser = new ArrayList<>();
        //遍历ID集合，查询用户具体信息
        for (Long userId : userIds) {
            User user = this.getById(userId);
            resultUser.add(user);
        }

        return resultUser;
    }


}

